<template>
  <div class="config">
    <a-card title="系统配置管理">
      <template #extra>
        <a-space>
          <a-button @click="handleReset" :loading="resetLoading">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置为默认
          </a-button>
          <a-button @click="handleValidate" :loading="validateLoading">
            <template #icon>
              <CheckCircleOutlined />
            </template>
            验证配置
          </a-button>
          <a-button 
            type="primary" 
            @click="handleSave" 
            :loading="saveLoading"
          >
            <template #icon>
              <SaveOutlined />
            </template>
            保存配置
          </a-button>
        </a-space>
      </template>

      <a-form
        :model="formData"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        class="config-form"
      >
        <!-- 服务器配置 -->
        <a-divider orientation="left">
          服务器配置
        </a-divider>
        
        <a-form-item label="服务端口" name="server.port">
          <a-input-number 
            v-model:value="formData.server.port" 
            :min="1000" 
            :max="65535"
            style="width: 200px"
            placeholder="3000"
          />
          <span style="margin-left: 8px; color: #666;">
            服务器监听端口
          </span>
        </a-form-item>
        
        <a-form-item label="服务主机" name="server.host">
          <a-input 
            v-model:value="formData.server.host" 
            placeholder="0.0.0.0"
          />
          <span style="margin-left: 8px; color: #666;">
            服务器绑定地址，0.0.0.0 表示所有接口
          </span>
        </a-form-item>

        <!-- Webhook配置 -->
        <a-divider orientation="left">
          <LinkOutlined />
          Webhook配置
        </a-divider>
        
        <a-form-item label="Webhook路径" name="webhook.path">
          <a-input 
            v-model:value="formData.webhook.path" 
            placeholder="/webhook"
            addon-before="http://your-server:port"
          />
        </a-form-item>
        
        <a-form-item label="Webhook密钥" name="webhook.secret">
          <a-input-password 
            v-model:value="formData.webhook.secret" 
            placeholder="用于验证webhook请求的密钥"
          />
          <div style="margin-top: 4px; color: #666; font-size: 12px;">
            用于验证来自Git平台的Webhook请求，确保安全性
          </div>
        </a-form-item>

        <a-form-item label="支持的Webhook类型" name="webhook.supportedTypes">
          <a-checkbox-group v-model:value="formData.webhook.supportedTypes">
            <a-checkbox value="github">GitHub</a-checkbox>
            <a-checkbox value="gitea">Gitea</a-checkbox>
            <a-checkbox value="gogs">Gogs</a-checkbox>
          </a-checkbox-group>
          <div style="margin-top: 4px; color: #666; font-size: 12px;">
            选择支持的Git平台类型
          </div>
        </a-form-item>

        <a-form-item label="自动检测类型" name="webhook.autoDetectType">
          <a-switch 
            v-model:checked="formData.webhook.autoDetectType"
            checked-children="启用"
            un-checked-children="禁用"
          />
          <span style="margin-left: 8px; color: #666;">
            自动检测Webhook来源类型
          </span>
        </a-form-item>

        <a-form-item label="签名验证" name="webhook.signatureVerification.enabled">
          <a-switch 
            v-model:checked="formData.webhook.signatureVerification.enabled"
            checked-children="启用"
            un-checked-children="禁用"
          />
          <span style="margin-left: 8px; color: #666;">
            启用Webhook签名验证
          </span>
        </a-form-item>

        <template v-if="formData.webhook.signatureVerification.enabled">
          <a-form-item label="强制签名" name="webhook.signatureVerification.requireSignature">
            <a-switch 
              v-model:checked="formData.webhook.signatureVerification.requireSignature"
              checked-children="必须"
              un-checked-children="可选"
            />
            <span style="margin-left: 8px; color: #666;">
              是否强制要求签名头
            </span>
          </a-form-item>
        </template>

        <a-form-item label="允许的事件" name="webhook.eventFiltering.allowedEvents">
          <a-select
            v-model:value="formData.webhook.eventFiltering.allowedEvents"
            mode="multiple"
            placeholder="选择允许的事件类型"
            style="width: 100%"
          >
            <a-select-option value="push">Push</a-select-option>
            <a-select-option value="pull_request">Pull Request</a-select-option>
            <a-select-option value="issues">Issues</a-select-option>
            <a-select-option value="release">Release</a-select-option>
            <a-select-option value="create">Create</a-select-option>
            <a-select-option value="delete">Delete</a-select-option>
          </a-select>
          <div style="margin-top: 4px; color: #666; font-size: 12px;">
            只处理选中的事件类型
          </div>
        </a-form-item>

        <a-form-item label="速率限制" name="webhook.security.rateLimiting.enabled">
          <a-switch 
            v-model:checked="formData.webhook.security.rateLimiting.enabled"
            checked-children="启用"
            un-checked-children="禁用"
          />
          <span style="margin-left: 8px; color: #666;">
            启用Webhook请求速率限制
          </span>
        </a-form-item>

        <template v-if="formData.webhook.security.rateLimiting.enabled">
          <a-form-item label="最大请求数" name="webhook.security.rateLimiting.maxRequests">
            <a-input-number 
              v-model:value="formData.webhook.security.rateLimiting.maxRequests" 
              :min="1" 
              :max="1000"
              style="width: 200px"
              placeholder="100"
            />
            <span style="margin-left: 8px; color: #666;">
              时间窗口内的最大请求数
            </span>
          </a-form-item>
          
          <a-form-item label="时间窗口" name="webhook.security.rateLimiting.windowMs">
            <a-input-number 
              v-model:value="formData.webhook.security.rateLimiting.windowMs" 
              :min="60000" 
              :max="3600000"
              :step="60000"
              style="width: 200px"
              placeholder="900000"
            />
            <span style="margin-left: 8px; color: #666;">
              毫秒 (1分钟 - 1小时)
            </span>
          </a-form-item>
        </template>

        <a-form-item label="IP白名单" name="webhook.security.ipWhitelist.enabled">
          <a-switch 
            v-model:checked="formData.webhook.security.ipWhitelist.enabled"
            checked-children="启用"
            un-checked-children="禁用"
          />
          <span style="margin-left: 8px; color: #666;">
            启用IP地址白名单限制
          </span>
        </a-form-item>

        <template v-if="formData.webhook.security.ipWhitelist.enabled">
          <a-form-item label="允许的IP" name="webhook.security.ipWhitelist.allowedIPs">
            <a-select
              v-model:value="formData.webhook.security.ipWhitelist.allowedIPs"
              mode="tags"
              placeholder="输入允许的IP地址，按回车添加"
              style="width: 100%"
            >
            </a-select>
            <div style="margin-top: 4px; color: #666; font-size: 12px;">
              只允许这些IP地址发送Webhook请求
            </div>
          </a-form-item>
        </template>

        <!-- Git仓库配置 -->
        <a-divider orientation="left">
          <GithubOutlined />
          Git仓库配置
        </a-divider>
        
        <a-form-item label="仓库URL" name="git.repositoryUrl">
          <a-input 
            v-model:value="formData.git.repositoryUrl" 
            placeholder="https://github.com/user/repo.git"
          />
        </a-form-item>
        
        <a-form-item label="目标分支" name="git.targetBranch">
          <a-input 
            v-model:value="formData.git.targetBranch" 
            placeholder="main"
          />
        </a-form-item>
        
        <a-form-item label="本地路径" name="git.localPath">
          <a-input 
            v-model:value="formData.git.localPath" 
            placeholder="./temp/repo"
          />
          <div style="margin-top: 4px; color: #666; font-size: 12px;">
            代码拉取到本地的临时目录
          </div>
        </a-form-item>
        
        <a-form-item label="部署路径" name="git.deployPath">
          <a-input 
            v-model:value="formData.git.deployPath" 
            placeholder="./public/dist"
          />
          <div style="margin-top: 4px; color: #666; font-size: 12px;">
            构建完成后文件复制到的目标目录
          </div>
        </a-form-item>

        <!-- Git认证配置 -->
        <a-divider orientation="left">
          <KeyOutlined />
          Git认证配置
        </a-divider>
        
        <a-form-item label="启用认证" name="git.auth.enabled">
          <a-switch 
            v-model:checked="formData.git.auth.enabled"
            checked-children="启用"
            un-checked-children="禁用"
          />
          <span style="margin-left: 8px; color: #666;">
            私有仓库需要启用认证
          </span>
        </a-form-item>

        <template v-if="formData.git.auth.enabled">
          <a-form-item label="认证类型" name="git.auth.type">
            <a-radio-group v-model:value="formData.git.auth.type">
              <a-radio value="ssh">SSH密钥</a-radio>
              <a-radio value="token">访问令牌</a-radio>
              <a-radio value="password">用户名密码</a-radio>
            </a-radio-group>
          </a-form-item>

          <!-- SSH认证 -->
          <template v-if="formData.git.auth.type === 'ssh'">
            <a-form-item label="SSH密钥路径" name="git.auth.sshKeyPath">
              <a-input 
                v-model:value="formData.git.auth.sshKeyPath" 
                placeholder="/path/to/private/key"
              />
              <div style="margin-top: 4px; color: #666; font-size: 12px;">
                私钥文件的绝对路径，权限应设置为600或400
              </div>
            </a-form-item>
          </template>

          <!-- Token认证 -->
          <template v-if="formData.git.auth.type === 'token'">
            <a-form-item label="访问令牌" name="git.auth.token">
              <a-input-password 
                v-model:value="formData.git.auth.token" 
                placeholder="ghp_xxxxxxxxxxxx"
              />
              <div style="margin-top: 4px; color: #666; font-size: 12px;">
                GitHub Personal Access Token、GitLab Access Token 等
              </div>
            </a-form-item>
          </template>

          <!-- 密码认证 -->
          <template v-if="formData.git.auth.type === 'password'">
            <a-form-item label="用户名" name="git.auth.username">
              <a-input 
                v-model:value="formData.git.auth.username" 
                placeholder="git用户名"
              />
            </a-form-item>
            <a-form-item label="密码" name="git.auth.password">
              <a-input-password 
                v-model:value="formData.git.auth.password" 
                placeholder="git密码"
              />
            </a-form-item>
          </template>

          <!-- 认证测试 -->
          <a-form-item label="认证测试" name="authTest">
            <a-button 
              @click="testAuthConfig" 
              :loading="authTestLoading"
              type="dashed"
            >
              <template #icon>
                <GlobalOutlined />
              </template>
              测试认证配置
            </a-button>
            <div v-if="authTestResult" style="margin-top: 8px;">
              <a-alert
                :message="authTestResult.message"
                :type="authTestResult.success ? 'success' : 'error'"
                show-icon
              />
            </div>
          </a-form-item>
        </template>

        <!-- 构建配置 -->
        <a-divider orientation="left">
          <BuildOutlined />
          构建配置
        </a-divider>
        
        <a-form-item label="构建命令" name="build.commands">
          <a-select
            v-model:value="formData.build.commands"
            mode="tags"
            placeholder="输入构建命令，按回车添加"
            style="width: 100%"
          >
            <a-select-option value="npm install">npm install</a-select-option>
            <a-select-option value="npm run build">npm run build</a-select-option>
            <a-select-option value="yarn install">yarn install</a-select-option>
            <a-select-option value="yarn build">yarn build</a-select-option>
            <a-select-option value="pnpm install">pnpm install</a-select-option>
            <a-select-option value="pnpm build">pnpm build</a-select-option>
          </a-select>
          <div style="margin-top: 4px; color: #666; font-size: 12px;">
            按顺序执行的构建命令列表
          </div>
        </a-form-item>
        
        <a-form-item label="构建超时" name="build.timeout">
          <a-input-number 
            v-model:value="formData.build.timeout" 
            :min="10000" 
            :max="1800000"
            :step="1000"
            style="width: 200px"
            placeholder="300000"
          />
          <span style="margin-left: 8px; color: #666;">
            毫秒 (10秒 - 30分钟)
          </span>
        </a-form-item>

        <!-- 服务配置 -->
        <a-divider orientation="left">
          <SettingOutlined />
          服务配置
        </a-divider>
        
        <a-form-item label="服务名称" name="service.name">
          <a-input 
            v-model:value="formData.service.name" 
            placeholder="web-service"
          />
        </a-form-item>
        
        <a-form-item label="重启命令" name="service.restartCommand">
          <a-input 
            v-model:value="formData.service.restartCommand" 
            placeholder="pm2 restart web-service"
          />
          <div style="margin-top: 4px; color: #666; font-size: 12px;">
            部署完成后执行的服务重启命令
          </div>
        </a-form-item>

        <!-- 日志配置 -->
        <a-divider orientation="left">
          <FileTextOutlined />
          日志配置
        </a-divider>
        
        <a-form-item label="日志级别" name="logging.level">
          <a-select v-model:value="formData.logging.level" style="width: 200px">
            <a-select-option value="error">Error</a-select-option>
            <a-select-option value="warn">Warn</a-select-option>
            <a-select-option value="info">Info</a-select-option>
            <a-select-option value="debug">Debug</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="日志文件" name="logging.file">
          <a-input 
            v-model:value="formData.logging.file" 
            placeholder="./logs/app.log"
          />
        </a-form-item>
        
        <a-form-item label="最大文件数" name="logging.maxFiles">
          <a-input-number 
            v-model:value="formData.logging.maxFiles" 
            :min="1" 
            :max="100"
            style="width: 200px"
            placeholder="10"
          />
        </a-form-item>
        
        <a-form-item label="最大文件大小" name="logging.maxSize">
          <a-input 
            v-model:value="formData.logging.maxSize" 
            placeholder="10m"
          />
          <div style="margin-top: 4px; color: #666; font-size: 12px;">
            支持格式：10m, 100k, 1g
          </div>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 配置验证结果 -->
    <a-modal
      v-model:open="validationModalVisible"
      title="配置验证结果"
      :footer="null"
      width="600px"
    >
      <div v-if="validationResult">
        <a-alert
          :message="validationResult.success ? '配置验证通过' : '配置验证失败'"
          :type="validationResult.success ? 'success' : 'error'"
          show-icon
          style="margin-bottom: 16px;"
        />
        
        <div v-if="validationResult.errors && validationResult.errors.length > 0">
          <h4>验证错误：</h4>
          <a-list
            :data-source="validationResult.errors"
            size="small"
          >
            <template #renderItem="{ item }">
              <a-list-item>
                <a-typography-text type="danger">{{ item }}</a-typography-text>
              </a-list-item>
            </template>
          </a-list>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import api from '../services/api'
import {
  SaveOutlined,
  ReloadOutlined,
  CheckCircleOutlined,
  GithubOutlined,
  KeyOutlined,
  BuildOutlined,
  FileTextOutlined,
  LinkOutlined,
  GlobalOutlined
} from '@ant-design/icons-vue'

// 响应式数据
const formData = ref({
  server: {
    port: 3000,
    host: '0.0.0.0'
  },
  webhook: {
    secret: '',
    path: '/webhook',
    supportedTypes: ['github', 'gitea', 'gogs'],
    autoDetectType: true,
    signatureVerification: {
      enabled: true,
      requireSignature: false,
      allowedTypes: ['github', 'gitea', 'gogs']
    },
    eventFiltering: {
      allowedEvents: ['push'],
      ignoredEvents: ['ping', 'issues', 'pull_request']
    },
    security: {
      rateLimiting: {
        enabled: false,
        maxRequests: 100,
        windowMs: 900000
      },
      ipWhitelist: {
        enabled: false,
        allowedIPs: []
      }
    }
  },
  git: {
    targetBranch: 'main',
    repositoryUrl: '',
    localPath: './temp/repo',
    deployPath: './public/dist',
    auth: {
      enabled: false,
      type: 'token',
      token: '',
      username: '',
      password: '',
      sshKeyPath: ''
    }
  },
  build: {
    commands: ['npm install', 'npm run build'],
    timeout: 300000
  },
  service: {
    name: 'web-service',
    restartCommand: 'pm2 restart web-service'
  },
  logging: {
    level: 'info',
    file: './logs/app.log',
    maxFiles: 10,
    maxSize: '10m'
  }
})

// 加载状态
const saveLoading = ref(false)
const resetLoading = ref(false)
const validateLoading = ref(false)
const authTestLoading = ref(false)

// 模态框状态
const validationModalVisible = ref(false)

// 结果数据
const validationResult = ref(null)
const authTestResult = ref(null)

// 方法
const loadConfig = async () => {
  try {
    const response = await api.getConfig()
    if (response.success) {
      formData.value = { ...formData.value, ...response.data }
    }
  } catch (error) {
    message.error('加载配置失败')
    console.error('加载配置失败:', error)
  }
}

const handleSave = async () => {
  try {
    saveLoading.value = true
    const response = await api.updateConfig(formData.value)
    if (response.success) {
      message.success('配置保存成功')
    } else {
      message.error(response.message || '保存配置失败')
    }
  } catch (error) {
    message.error('保存配置失败')
    console.error('保存配置失败:', error)
  } finally {
    saveLoading.value = false
  }
}

const handleReset = async () => {
  try {
    resetLoading.value = true
    const response = await api.resetConfig()
    if (response.success) {
      message.success('配置已重置为默认值')
      await loadConfig()
    } else {
      message.error(response.message || '重置配置失败')
    }
  } catch (error) {
    message.error('重置配置失败')
    console.error('重置配置失败:', error)
  } finally {
    resetLoading.value = false
  }
}

const handleValidate = async () => {
  try {
    validateLoading.value = true
    const response = await api.validateConfig(formData.value)
    validationResult.value = response
    validationModalVisible.value = true
    
    if (response.success) {
      message.success('配置验证通过')
    } else {
      message.error('配置验证失败')
    }
  } catch (error) {
    message.error('验证配置失败')
    console.error('验证配置失败:', error)
  } finally {
    validateLoading.value = false
  }
}

const testAuthConfig = async () => {
  if (!formData.value.git.auth.enabled) {
    message.warning('请先启用认证')
    return
  }

  try {
    authTestLoading.value = true
    authTestResult.value = null
    
    const authConfig = {
      enabled: formData.value.git.auth.enabled,
      type: formData.value.git.auth.type,
      token: formData.value.git.auth.token,
      username: formData.value.git.auth.username,
      password: formData.value.git.auth.password,
      sshKeyPath: formData.value.git.auth.sshKeyPath
    }
    
    const response = await api.validateAuthConfig(authConfig)
    authTestResult.value = response
    
    if (response.success) {
      message.success('认证配置测试通过')
    } else {
      message.error('认证配置测试失败')
    }
  } catch (error) {
    authTestResult.value = {
      success: false,
      message: '测试请求失败'
    }
    message.error('认证测试失败')
    console.error('认证测试失败:', error)
  } finally {
    authTestLoading.value = false
  }
}

// 生命周期
onMounted(async () => {
  await loadConfig()
})
</script>

<style scoped>
.config {
  padding: 24px;
}

.config-form {
  max-width: 800px;
}

.config-form .ant-divider {
  margin: 32px 0 24px 0;
}

.config-form .ant-divider:first-child {
  margin-top: 0;
}

.config-form .ant-form-item {
  margin-bottom: 24px;
}

.config-form .ant-input-number {
  width: 100%;
}

.config-form .ant-select {
  width: 100%;
}
</style>